#include "_SoundEffect.h"
#ifdef _ANDROID_PLATFORM__
#include "SDL_log.h"
#else
#include <SDL2/SDL_log.h>
#endif

void _SoundEffect::loadSound(std::string soundId, std::string fileName) {
  //如果不存在
  if (chunk_list.find(soundId) == chunk_list.end()) {
    Mix_Chunk* chunk = Mix_LoadWAV(fileName.c_str());
    if (chunk != nullptr) {
      chunk_list.insert(std::pair<std::string, Mix_Chunk*>(soundId, chunk));
    } else {
      SDL_LogError(0, "音效文件加载失败,id:%s,%s\n", soundId.c_str(),
                   SDL_GetError());
    }
  } else {
    SDL_LogError(0, "此音效已加载或id已被占用:id:%s\n", soundId.c_str());
  }
}
void _SoundEffect::playSound(std::string soundId, bool isLoop) {
  //正在播放的数量
  int playingChannels = 0;
  for (int i = 0; i < channelnum; i++) {
    if (Mix_Playing(i)) {
      playingChannels++;
    }
  }
  //如果还剩下4个空通道，就自动扩充8个
  if (channelnum - playingChannels == 4) {
    Mix_AllocateChannels(channelnum += 8);
  }
  Mix_PlayChannel(-1, chunk_list[soundId], 0);
}
_SoundEffect::~_SoundEffect() {
  for (auto i : chunk_list) {
    Mix_FreeChunk(i.second);
  }
}